package com.tedu.springboot2303.controller;

import com.tedu.springboot2303.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

/*
* UserController用于处理所有与用户有关的请求 */
@Controller
public class UserController {
    private static File userDir;//表示存放所有用户信息的目录：users
    static {
        userDir = new File("./users");
        if(!userDir.exists()){
            userDir.mkdir();
        }
    }
    @RequestMapping("/regUser")
    public void reg(HttpServletRequest request, HttpServletResponse response){
        System.out.println("开始处理用户注册！！！");
        /*
        * 1.获取浏览器表单中提交的数据
        * 2.将数据保存到磁盘上
        * 3.给用户发送一个处理结果页面*/
        //1.获取浏览器表单数据，这里getParameter中传递的参数与页面输入框名字一致
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String nickname = request.getParameter("nickname");
        String ageStr = request.getParameter("age");
        //必要的验证
        if( username==null || username.isEmpty() ||
            password==null || password.isEmpty() ||
            nickname==null || nickname.isEmpty() ||
            ageStr==null || ageStr.isEmpty() || !ageStr.matches("[0-9]+")
        ){
            try {
                response.sendRedirect("/reg_info_error.html");
                return;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println(username+','+password+','+nickname+','+ageStr);
        int age = Integer.parseInt(ageStr); //将年龄转换为int值
        //2.
        User user = new User(username,password,nickname,age);
        /*
        * File的构造器
        * File(File parent,String child)
        * 创建一个File对象表示child这个子项，而它是在parent这个File对象所表示的目录中*/
        File file = new File(userDir,username+".obj");
        if(file.exists()){
            try {
                response.sendRedirect("/have_user.html");
                return;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try(
                FileOutputStream fos = new FileOutputStream(file);
                ObjectOutputStream oos = new ObjectOutputStream(fos);
                ) {
            oos.writeObject(user); //保存用户信息完毕
            //3.给用户回馈注册成功页面
            //要求浏览器重新访问下述地址对应的页面
            response.sendRedirect("/reg_success.html");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    @RequestMapping("/loginUser")
    public void login(HttpServletRequest request, HttpServletResponse response){
        System.out.println("开始处理用户登录！！！");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println(username+password);
        if(username==null||username.isEmpty()||password==null||password.isEmpty()){
            try {
                response.sendRedirect(".login_info_error.html");
                return;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        File file = new File(userDir,username+".obj");
        if(file.exists()){
            //读取该文件并反序列化其中保存的user对象(该对象记录了曾经该用户的注册信息)
            try(
                    FileInputStream fis = new FileInputStream(file);
                    ObjectInputStream ois = new ObjectInputStream(fis);
            ) {
                User user = (User)ois.readObject();
                if(user.getPassword().equals(password)){
                    response.sendRedirect("/login_success.html");
                    return;
                }
            } catch (IOException | ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
        //文件不存在说明该用户不存在--登录失败
        try {
            response.sendRedirect("/login_fail.html");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @RequestMapping("/userList")
    public void userList(HttpServletRequest request,HttpServletResponse response){
        System.out.println("开始处理用户列表");
        List<User> userList  = new ArrayList<>();
        File[] subs = userDir.listFiles(f->f.getName().endsWith(".obj"));
        for(File sub : subs){
            try (
                    FileInputStream fis = new FileInputStream(sub);
                    ObjectInputStream ois = new ObjectInputStream(fis);
                    ) {
                try {
                    User user = (User)ois.readObject();
                    userList.add(user);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            response.setContentType("text/html;charset=utf-8");
            PrintWriter pw = response.getWriter();
            pw.println("<!DOCTYPE html>");
            pw.println("<html lang=\"en\">");
            pw.println("<head>");
            pw.println("<meta charset=\"UTF-8\">");
            pw.println("<title>用户列表</title>");
            pw.println("</head>");
            pw.println("<body>");
            pw.println("<center>");
            pw.println("<h1>用户列表</h1>");
            pw.println("<table border=\"1\">");
            pw.println("<tr>");
            pw.println("<td>用户名</td>");
            pw.println("<td>密码</td>");
            pw.println("<td>昵称</td>");
            pw.println("<td>年龄</td>");
            pw.println("</tr>");
            for (User user : userList){
                pw.println("<tr>");
                pw.println("<td>"+user.getUsername()+"</td>");
                pw.println("<td>"+user.getPassword()+"</td>");
                pw.println("<td>"+user.getNickname()+"</td>");
                pw.println("<td>"+user.getAge()+"</td>");
                pw.println("</tr>");
            }
            pw.println("</table>");
            pw.println("</center>");
            pw.println("</body>");
            pw.println("</html>");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
